<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue'
import { useLevelStore } from '@/stores/level'
import { Search } from '@element-plus/icons-vue'
import { 
    getSubjectList, 
    getExamPaperPage, 
    examPaperDelete,
    type Subject, 
    type ExamPaperItem 
} from '@/api/juanti'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router' // 添加路由功能

const router = useRouter() // 获取路由实例
const LevelStore = useLevelStore()

// 表单参数
const formInline = reactive({
    questionId: '',
    gradeLevel: null as number | null,
    subject: '' as string | number,
})

// 分页参数
const pageParams = reactive({
    pageIndex: 1,
    pageSize: 10
})

// 试卷数据
const tableData = ref<ExamPaperItem[]>([])
const total = ref(0)

// 学科列表数据
const subjectList = ref<Subject[]>([])
// 筛选后的学科选项
const subjectOptions = ref<{ value: number; label: string }[]>([])
// 加载状态
const loading = ref(false)

// 加载学科数据
const loadSubjects = async () => {
    try {
        loading.value = true
        const response = await getSubjectList()
        
        // 确保响应有效
        if (response?.code === 1 && Array.isArray(response?.response)) {
            subjectList.value = response.response
            filterSubjects()
        } else {
            console.error('无效的学科列表响应:', response)
            subjectList.value = []
        }
    } catch (error) {
        console.error('加载学科列表失败:', error)
        subjectList.value = []
    } finally {
        loading.value = false
    }
}

// 根据年级筛选学科
const filterSubjects = () => {
    if (formInline.gradeLevel) {
        // 筛选当前年级的学科
        subjectOptions.value = subjectList.value
            .filter(item => item.level === formInline.gradeLevel)
            .map(item => ({
                value: item.id,
                label: item.name
            }))
    } else {
        // 未选择年级时清空学科选项
        subjectOptions.value = []
        formInline.subject = ''
    }
    
    // 如果当前选择的学科不在新列表中，则清空选择
    if (formInline.subject && 
        !subjectOptions.value.some(opt => opt.value === formInline.subject)) {
        formInline.subject = ''
    }
}

// 获取学科名称
const getSubjectName = (subjectId: number): string => {
    const subject = subjectList.value.find(item => item.id === subjectId)
    return subject ? subject.name : '未知学科'
}

// 加载试卷数据
const loadExamPapers = async () => {
    try {
        loading.value = true
        
        const params = {
            id: formInline.questionId || null,
            level: formInline.gradeLevel,
            subjectId: formInline.subject ? Number(formInline.subject) : null,
            pageIndex: pageParams.pageIndex,
            pageSize: pageParams.pageSize
        }
        
        const response = await getExamPaperPage(params)
        
        if (response?.code === 1 && response.response) {
            tableData.value = response.response.list || []
            total.value = response.response.total || 0
        } else {
            console.error('试卷列表获取失败:', response)
            tableData.value = []
            total.value = 0
        }
    } catch (error) {
        console.error('加载试卷列表失败:', error)
        tableData.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

// 删除试卷
const handleDelete = (id: number) => {
    ElMessageBox.confirm('确定要删除这张试卷吗？此操作不可撤销。', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            const response = await examPaperDelete(id)
            
            if (response?.code === 1) {
                ElMessage.success('试卷删除成功')
                // 重新加载数据
                loadExamPapers()
            } else {
                ElMessage.error(`删除失败: ${response?.message || '未知错误'}`)
            }
        } catch (error) {
            console.error('删除试卷失败:', error)
            ElMessage.error('删除试卷失败，请稍后再试')
        }
    }).catch(() => {
        // 用户取消操作
    })
}

// 跳转到编辑试卷页面
const goToEditShijuan = (id: number) => {
    router.push(`/shijuanedit/${id}`)
}

// 监听年级变化
watch(() => formInline.gradeLevel, () => {
    filterSubjects()
})

// 初始化加载数据
onMounted(() => {
    loadSubjects()
    loadExamPapers()
})

// 查询提交
const onSubmit = () => {
    pageParams.pageIndex = 1
    loadExamPapers()
}

// 跳转到添加试卷页面
const goToAddShijuan = () => {
    router.push('/shijuanadd')
}

// 页码变化处理
const handlePageChange = (currentPage: number) => {
    pageParams.pageIndex = currentPage
    loadExamPapers()
}
</script>

<template>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
            <h3>题目ID:</h3>
            <div style="width: 10px;"></div>
            <el-input 
                v-model="formInline.questionId" 
                style="width: 200px" 
                placeholder="请输入题目ID"
            />
        </el-form-item>
        <el-form-item>
            <h3>年级:</h3>
            <div style="width: 10px;"></div>
            <el-select 
                v-model="formInline.gradeLevel" 
                style="width: 200px" 
                clearable
                placeholder="请选择年级"
                :loading="loading"
            >
                <el-option 
                    v-for="item in LevelStore.list" 
                    :key="item.value" 
                    :label="item.name" 
                    :value="item.value" 
                />
            </el-select>
        </el-form-item>
        
        <!-- 只在年级被选择时才渲染学科下拉框 -->
        <el-form-item v-if="formInline.gradeLevel">
            <h3>学科:</h3>
            <div style="width: 10px;"></div>
            <el-select 
                v-model="formInline.subject" 
                style="width: 200px"
                placeholder="请选择学科"
                :loading="loading"
                clearable
            >
                <el-option 
                    v-for="item in subjectOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" 
                />
            </el-select>
        </el-form-item>
        
        <el-form-item>
            <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
            <el-button type="primary" @click="goToAddShijuan">添加</el-button>
        </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="Id" width="180" />
        <el-table-column prop="name" label="名称" />
        <el-table-column label="学科" width="180">
            <template #default="{ row }">
                {{ getSubjectName(row.subjectId) }}
            </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column fixed="right" label="操作">
            <template #default="{ row }">
                <el-button @click="goToEditShijuan(row.id)">编辑</el-button>
                <el-button type="danger" @click="handleDelete(row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div style="margin-top: 20px; display: flex; justify-content: center;">
        <el-pagination 
            background 
            layout="prev, pager, next" 
            :total="total"
            :current-page="pageParams.pageIndex"
            :page-size="pageParams.pageSize"
            @current-change="handlePageChange"
        />
    </div>
</template>